package com.Pan;

import cn.hutool.core.io.FileUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectResult;
import com.Pan.mapper.PecUrlMapper;
import com.Pan.pojo.PecUrl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.NTCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

/**
 * @author lipanJia
 * @date 2021-11-29 16:14
 */
@SpringBootTest
@Slf4j
public class OssUploading {

    @Autowired
    private OSS ossClient;

    @Value("${cloudStorage.aliyunOSS.bucketName}")
    private String bucketName;

    @Value("${cloudStorage.aliyunOSS.domain}")
    private String aliyunDomain;

    @Autowired
    private PecUrlMapper pecUrlMapper;


    /**
     * 遍历文件夹并上传oss写路径
     *
     * @throws JSONException
     * @throws InterruptedException
     */
    @Test
    void contextLoadPicture() throws JSONException, InterruptedException {
        // 取路径
        File file = new File("E:\\传图文件夹\\原图2.0 - 副本");
        File[] files = file.listFiles();
        log.info("图片路径为: {}", files);
        int i = 0;
        for (File file1 : files) {
            PecUrl pecUrl = new PecUrl();
            try {
                String key = "123456asdf/20211129PECURL/" + file1.getName();
                InputStream inputStream = new FileInputStream(file1);
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, inputStream);
                pecUrl.setImgUrl(aliyunDomain + "/" + key);
                pecUrl.setId(++i);
                pecUrlMapper.insert(pecUrl);
            } catch (Exception e) {
                log.info("文件上传OSS异常!, {}", e);
            }
        }
    }

    /**
     * 遍历文件夹并上传oss写路径
     *
     * @throws JSONException
     * @throws InterruptedException
     */
    @Test
    void contextOssPicture() {
        // 取路径
        File file = new File("E:\\传图文件夹\\原图2.0 - 副本");
        File[] files = file.listFiles();
        log.info("图片路径为: {}", files);
        int i = 0;
        for (File file1 : files) {
            PecUrl pecUrl = new PecUrl();
            try {
                String key = "123456asdf/20211129PECURL/" + file1.getName();
                InputStream inputStream = new FileInputStream(file1);
                PutObjectResult putObjectResult = ossClient.putObject(bucketName, key, inputStream);
                pecUrl.setImgUrl(aliyunDomain + "/" + key);
                pecUrl.setId(++i);
                pecUrlMapper.insert(pecUrl);
            } catch (Exception e) {
                log.info("文件上传OSS异常!, {}", e);
            }
        }
    }

    @Test
    void downloadPicture() {
        LambdaQueryWrapper<PecUrl> pecUrlLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<PecUrl> pecUrls = pecUrlMapper.selectList(pecUrlLambdaQueryWrapper);
        for (PecUrl pecUrl : pecUrls) {
            String imgUrl = pecUrl.getImgUrl();
            String name = imgUrl.substring(imgUrl.lastIndexOf("/") + 1);
            downloadCompressFile(imgUrl, name);
        }
    }

    public static String downloadCompressFile(String url, String name) {

        // 生成基础路径
        String savePath = "D:\\image\\perfetti" + File.separator  + name;
        log.info("下载路径本地路径:{}, 原始URL:{}", savePath, url);


        String sa = url.trim().replace(" ", "");
        url = sa.replace("\t", "%20");
        log.info("下载原图链接:{}, 目标地址:{}", url, savePath);

        // 生产
        try {
            log.info("下载文件开始, URL:{}", url);
            SSLContext sslContext = null;
            try {
                sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true).build();
            } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
                e.printStackTrace();
            }
            HttpPost request = new HttpPost(url);
            RequestConfig config = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
            request.setConfig(config);
            NTCredentials creds = new NTCredentials("Trax.AIPhoto@cn.pvmgrp.com", "Twenty-a=A", "", "");

            CredentialsProvider provider = new BasicCredentialsProvider();
            provider.setCredentials(AuthScope.ANY, creds);
            CloseableHttpClient client = HttpClientBuilder.create()
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext)).setDefaultCredentialsProvider(provider).build();

            CloseableHttpResponse response = null;
            response = client.execute(request);
            InputStream content = response.getEntity().getContent();
            log.info("下载文件完成, URL:{}", url);
            FileUtil.writeFromStream(content, savePath);
            log.info("写入本地完成, URL:{}, 本地路径:{}", url, savePath);
        } catch (Exception e) {
            log.error("下载文件失败, URL:{}, e:{}", url, e);
        }
        return "success";
    }

}
